package br.com.galluzzo;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;


@Path("/sparql")
public class SparqlQueryResource {
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String executar(@QueryParam("query") String consulta,@QueryParam("sparqlendpoint") String endpoint) {
		String resposta = "";
		
		Query query = QueryFactory.create(consulta);
		QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);
		ResultSet rs = qexec.execSelect();
		JSONObject principal = new JSONObject();
		
		List<String> vars =  rs.getResultVars();
		JSONArray ja = new JSONArray();
		while(rs.hasNext()) {
			JSONObject jo = new JSONObject();	
			for (String var : vars) {
				Resource varResource = rs.next().getResource(var);
				try {
								
					JSONObject o = new JSONObject();
					o.put("URI",varResource.getURI() );
					o.put("Nome", varResource.getLocalName());
					jo.put(var,o );
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				
			}
			ja.put(jo);
		}
		try {
			principal.put("Result", ja);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ja.toString();
	}
}
